package com.example.demo.others.git;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.eclipse.jgit.api.Git;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

@Component
public class AutoPushUtil {

    public static String base_source_dir;
    public static String tag_format_date;

    @Value("${base_source_dir}")
    public void setBase_source_dir(String base_source_dir) {
        AutoPushUtil.base_source_dir = base_source_dir;
    }

    @Value("${tag_format_date}")
    public   void setTag_format_date(String tag_format_date) {
        AutoPushUtil.tag_format_date = tag_format_date;
    }

    static Logger logger = LoggerFactory.getLogger(AutoPushUtil.class);


    /**
     * @param dir      目标目录
     * @param sour_jar 原文件
     * @param tar_jar  目标文件
     * @param depends  依赖
     * @return
     */
    public static JSONObject create(String dir, String sour_jar, String tar_jar, List<JSONObject> depends) {
        JSONObject j = new JSONObject();
        j.put("dir", dir);
        tar_jar = StringUtils.isBlank(tar_jar) ? sour_jar : tar_jar;
        j.put("tar_jar", tar_jar);
        j.put("sour_jar", sour_jar);
        j.put("depens", depends);
        return j;
    }

    /**
     * 创建依赖
     *
     * @param dir      目标目录
     * @param sour_jar 原文件
     * @param tar_jar  目标文件
     * @return
     */
    public static List<JSONObject> createDepens(String dir, String sour_jar, String tar_jar) {
        List<JSONObject> res = new ArrayList<>();
        String[] s = sour_jar.split(",");
        String[] t = tar_jar.split(",");
        for (int i = 0; i < s.length; i++) {
            res.add(create("", s[i], dir + t[i], null));
        }
        return res;
    }


    public static JSONObject createFile(String sour_jar, String tar_jar) {
        JSONObject f = new JSONObject();
        f.put("sour_jar", sour_jar);
        f.put("tar_jar", tar_jar);
        return f;
    }

    public JSONObject push(Map<String, String> params, List<JSONObject> files) throws Exception {

        String name = params.get("name");
        String pack_dir = params.get("pack_dir");

        String base_target_dir = params.get("base_target_dir");
        String tagPrefix = params.get("tagPrefix");
        String msgPrefix = params.get("msgPrefix");
        String pushMessage = params.get("pushMessage");


        final JSONObject j = new JSONObject();
        j.put("pack_dir", pack_dir);
        files = files.stream().filter(f -> {
            boolean exists = Files.exists(Paths.get(base_source_dir + f.getString("sour_jar")));
            return exists;
        }).collect(Collectors.toList());
        int size = files.size();
        if (size <= 0) {
            logger.info("no file be found , return ");
            j.put("msg", "no file be found");

            throw new RuntimeException("no file be found");
        }
        String localRepo = base_target_dir + pack_dir + "\\";
        try {
            GitUtil.pull(name, localRepo);
        } catch (Exception e) {
            logger.info("pull err:{}", e);
            j.put("msg", "git pull err," + e);
            return j;
        }
        files.forEach(f -> {


            String s = base_source_dir + f.getString("sour_jar");
            String t = localRepo + f.getString("tar_jar");
            logger.info("move file ,sou_file:{},tar_file:{}", s, t);
            try {

                Files.move(Paths.get(s), Paths.get(t), StandardCopyOption.REPLACE_EXISTING);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

        });


        String tag = tagPrefix + DateFormatUtils.format(Instant.now().toEpochMilli(), tag_format_date);
//            GitUtil.commitFiles(name, localRepo, msgPrefix + pushMessage, tag, pushMessage);
        Git git = GitUtil.open(localRepo);
        GitUtil.commit(git, msgPrefix + pushMessage, tag, pushMessage);
        GitUtil.push(name, git);
        git.close();
        j.put("tag", tag);

        j.put("msg", "success");

        return j;

    }


    public List<JSONObject> run(Map<String, String> params, JSONObject p) throws Exception {


        List<JSONObject> res = new ArrayList<>();
        params.put("pack_dir", p.getString("dir"));

        List<JSONObject> depens = (ArrayList) p.get("depens");
        List<JSONObject> files = new ArrayList<>();
        files.add(AutoPushUtil.createFile(p.getString("sour_jar"), p.getString("tar_jar")));
        if (depens != null && !depens.isEmpty()) {

            depens.forEach(d -> {
                files.add(AutoPushUtil.createFile(d.getString("sour_jar"), d.getString("tar_jar")));
            });
        }
        JSONObject j = push(params, files);

        res.add(j);

        return res;


    }


}
